<template>
  <view style="background-color: #ffffff">
    <u-form ref="form" :model="form" class="form-view" label-position="top">
      <u-form-item
        prop="enterpriseName"
        class="form-item clearfix"
        label="企业名称"
      >
        <view class="form-value">
          <input
            type="text"
            placeholder="请输入企业名称"
            placeholder-class="input-pl"
            class="form-input"
            v-model="form.enterpriseName"
          />
          <i class="ibonfont ibonjinru icon-jinru"></i>
        </view>
      </u-form-item>
      <u-form-item prop="brandName" class="form-item clearfix" label="品牌名称">
        <view class="form-value">
          <input
            type="text"
            placeholder="请输入品牌名称"
            placeholder-class="input-pl"
            class="form-input"
            v-model="form.brandName"
          />
          <i class="ibonfont ibonjinru icon-jinru"></i>
        </view>
      </u-form-item>
      <u-form-item prop="brandName" class="form-item clearfix" label="店铺类型">
        <view class="form-value">
          <radio-group
            name="radio"
            class="dianPuLeiXing"
            @change="dianPuLeiXing"
          >
            <label :class="form.scope === '4' ? 'radio_active' : ''">
              <radio
                value="4"
                :checked="form.scope === '4' ? true : false"
              /><text>单店铺</text>
            </label>
            <label :class="form.scope === '5' ? 'radio_active' : ''">
              <radio
                value="5"
                :checked="form.scope === '5' ? true : false"
              /><text>连锁店</text>
            </label>
          </radio-group>
        </view>
      </u-form-item>
      <u-form-item prop="contact" class="form-item clearfix" label="联系人">
        <view class="form-value">
          <input
            type="text"
            placeholder="请输入联系人"
            placeholder-class="input-pl"
            class="form-input"
            v-model="form.contact"
          />
          <i class="ibonfont ibonjinru icon-jinru"></i>
        </view>
      </u-form-item>
      <u-form-item prop="mobile" class="form-item clearfix" label="联系电话">
        <view class="form-value">
          <input
            type="number"
            placeholder="请输入联系电话"
            placeholder-class="input-pl"
            class="form-input"
            v-model="form.mobile"
          />
          <i class="ibonfont ibonjinru icon-jinru"></i>
        </view>
      </u-form-item>
      <u-form-item prop="mobile" class="form-item clearfix" label="所属区域">
        <view class="form-value" @click="regionOpen">
          <text v-if="regionName">{{ regionName }}</text>
          <text class="input-pl" v-else>请选择所属区域</text>
          <RegionSel
            v-model="region_show"
            @confirm="regionConfirm"
            @cancel="regionCancel"
          ></RegionSel>
          <i class="ibonfont ibonjinru icon-jinru"></i>
        </view>
      </u-form-item>
      <u-form-item prop="address" class="form-item clearfix" label="详细地址">
        <view class="form-value">
          <input
            type="text"
            placeholder="请输入详细地址"
            placeholder-class="input-pl"
            class="form-input"
            v-model="form.address"
          />
          <i class="ibonfont ibonjinru icon-jinru"></i>
        </view>
      </u-form-item>
      <u-form-item
        prop="categoryId"
        class="form-item clearfix"
        label="企业类别"
      >
        <view class="form-value">
          <picker
            @change="storeChange"
            @columnchange="columnChange"
            :value="index"
            :range="storeTypeList"
            range-key="label"
          >
            <text class="sel-label sel-name" v-if="categoryStore">{{
              categoryStore
            }}</text>
            <text class="input-pl" v-else>请选择企业类别</text>
            <i class="ibonfont ibonjinru icon-jinru"></i>
          </picker>
        </view>
      </u-form-item>
      <view class="form-up">
        <view class="form-label">
          营业时间：
          <text class="icon-requird">*</text>
        </view>
        <view class="form-value clearfix">
          <view class="float_left form-value" @click="showTime = true">
            <picker
              mode="time"
              start="8:00"
              end="24:00"
              @change="startTimeChange"
              ref="endtime"
            >
              <view class="TimeBorder" v-if="form.startTime">{{
                form.startTime
              }}</view>
              <view class="input-pl TimeBorder" v-else>开始时间</view>
            </picker>
          </view>
          <view class="float_left line">-</view>
          <view class="float_left form-value">
            <picker
              mode="time"
              start="8:00"
              end="24:00"
              @change="endTimeChange"
              ref="endtime"
            >
              <view class="TimeBorder" v-if="form.endTime">{{
                form.endTime
              }}</view>
              <view class="input-pl TimeBorder" v-else>结束时间</view>
            </picker>
          </view>
        </view>
      </view>
      <view class="form-up">
        <view class="form-label">
          企业LOGO（仅可上传一张）
          <text class="icon-requird">*</text>
        </view>
        <view class="form-value clearfix">
          <!-- <image v-if="form.logo" class="cata-img float_left" :src="form.logo" mode="aspectFill"></image> -->
          <QiniuUpload
            :count="1"
            @uploadSuccess="uploadSuccess"
            @handleRemove="uploadRemove"
            :images="[form.logo]"
          >
            <view slot="cont" class="upload-view"
              ><i class="ibonfont ibonxinzeng"></i
            ></view>
          </QiniuUpload>
        </view>
      </view>
    </u-form>
    <view class="fixed-bottom"
      ><view class="sub-btn" @click="submitData">保存</view></view
    >
  </view>
</template>

<script>
import QiniuUpload from "@/components/qiniu/QiniuUpload.vue";
import url from "@/common/config.js";
import RegionSel from "@/components/region/RegionSel.vue";
export default {
  components: {
    QiniuUpload,
    RegionSel,
  },
  data() {
    return {
      region_show: false,
      enterpriseId: 0,
      regionName: "",
      categoryStore: "",
      storeTypeList: [],
      index: 0, // 新增：picker选中项索引
      form: {
        scope: "4", // 店铺类型: '4'代表单店铺, '5'代表多店铺, 默认单店铺
        brandName: "",
        enterpriseName: "",
        contact: "",
        mobile: "",
        provinceCode: "",
        cityCode: "",
        districtCode: "",
        address: "",
        categoryId: "",
        startTime: "",
        endTime: "",
        logo: "",
      },
      supplierName: "",
      rules: {
        enterpriseName: {
          required: true,
          message: "请输入企业名称",
        },
        contact: {
          required: true,
          message: "请输入联系人",
        },
        mobile: {
          required: true,
          message: "请输入联系电话",
        },
        provinceCode: {
          required: true,
          message: "请选择所属区域",
        },
        address: {
          required: true,
          message: "请输入详细地址",
        },
        categoryId: {
          required: true,
          message: "请选择企业类别",
        },
        startTime: {
          required: true,
          message: "请选择营业时间",
        },
        logo: {
          required: true,
          message: "请上传LOGO",
        },
      },
    };
  },
  onShow() {},
  onLoad(options) {
    // 表单验证
    this.$nextTick(() => {
      this.$refs.form.setRules(this.rules);
    });

    this.getAllEnterpriseCategory();
    console.log(options);
    if (options.id) {
      this.enterpriseId = options.id;
      this.getDetail();
      uni.setNavigationBarTitle({
        title: "编辑企业",
      });
    } else {
      uni.setNavigationBarTitle({
        title: "创建企业",
      });
    }
  },

  methods: {
    // 营业时间
    startTimeChange(e) {
      this.form.startTime = e.detail.value;
    },
    endTimeChange(e) {
      this.form.endTime = e.detail.value;
    },
    // 时间戳转HH:mm
    timestampToTime(ts) {
      if (!ts) return "";
      // 兼容10位和13位时间戳
      if (String(ts).length === 10) ts = ts * 1000;
      const date = new Date(Number(ts));
      const h = date.getHours().toString().padStart(2, "0");
      const m = date.getMinutes().toString().padStart(2, "0");
      return `${h}:${m}`;
    },
    // 企业类别
    async getAllEnterpriseCategory() {
      const { err, data } = await this.$u.api.getAllEnterpriseCategory();
      if (err) return;
      if (data.length == 0) return;
      this.storeTypeList = data.map((item) => {
        return {
          value: item.id,
          label: item.name,
        };
      });
    },
    regionConfirm(val) {
      this.form.provinceCode = val[0].value;
      this.form.cityCode = val[1].value;
      this.form.districtCode = val[2].value;
      this.regionName = [val[0].label, val[1].label, val[2].label].join("-");
    },
    regionCancel() {
      this.region_show = false;
    },
    regionOpen() {
      this.region_show = true;
    },
    storeChange(e) {
      // 兼容picker返回
      if (
        typeof e === "object" &&
        e.detail &&
        typeof e.detail.value === "number"
      ) {
        const idx = e.detail.value;
        this.index = idx;
        const item = this.storeTypeList[idx];
        this.categoryStore = item ? item.label : "";
        this.form.categoryId = item ? item.value : "";
      } else {
        // 兼容原有逻辑
        this.categoryStore = e.value ? e.label : "";
        this.form.categoryId = e.value;
      }
    },
    // 上传图片
    uploadSuccess(res) {
      const uploadPicUrl = this.$store.state.getStorage.config.domain + `/${res.key}`;
      this.form.logo = uploadPicUrl;
    },
    uploadRemove(res) {
      this.form.logo = "";
    },
    // 获取详情
    async getDetail() {
      console.log(this.enterpriseId);
      const { err, data } = await this.$u.api.getEnterpriseInfo(
        this.enterpriseId,
        {}
      );
      if (err) return;
      // 处理营业时间为10位时间戳的情况
      this.form = {
        ...this.form,
        ...data,
        startTime: this.timestampToTime(data.startTime),
        endTime: this.timestampToTime(data.endTime),
      };
      this.regionName = [
        data.area.provinceName,
        data.area.cityName,
        data.area.districtName,
      ].join("-");
      // 企业类别id
      const idx = this.storeTypeList.findIndex(
        (item) => item.value == data.categoryId
      );
      if (idx > -1) {
        this.categoryStore = this.storeTypeList[idx].label;
        this.index = idx;
      } else {
        this.categoryStore = "";
        this.index = 0;
      }
      // 店铺类型（接口返回int，需转字符串）
      this.form.scope = data.scope !== undefined ? String(data.scope) : "4";
    },
    // 提交
    async submitData() {
      console.log(this.form, this.$refs.form);
      //   this.$refs.form.validate(async (res) => {
      //     if (res) {
      if (!this.form.startTime || !this.form.endTime) {
        this.$u.toast("请选择营业时间");
        return;
      }
      if (!this.form.logo) {
        this.$u.toast("请上传LOGO");
        return;
      }

      let target = {};
      if (this.enterpriseId) {
        target = await this.$u.api.updateEnterprise(this.form);
      } else {
        target = await this.$u.api.addEnterprise(this.form);
      }
      uni.showLoading();
      const { err, data } = target;
      uni.hideLoading();
      if (err) return;
      this.$u.toast("提交成功");
      uni.navigateBack();
      //     }
      //   });
    },
    dianPuLeiXing(e) {
      this.form.scope = e.detail.value;
    },
  },
};
</script>

<style lang="scss">
$main-color: #fb5904;
$bg-color: #ffffff;

.form-view {
  background: $bg-color;
  padding: 24rpx 32rpx 120rpx 32rpx;
  min-height: 100vh;
}

.form-item {
  margin-bottom: 32rpx;
  background: $bg-color;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(251, 89, 4, 0.04);
  .form-label {
    color: #333;
    font-size: 30rpx;
    font-weight: 500;
    margin-bottom: 12rpx;
    display: flex;
    align-items: center;
    .icon-requird {
      color: $main-color;
      margin-left: 8rpx;
      font-size: 24rpx;
    }
  }
  .form-value {
    display: flex;
    align-items: center;
    background: #ffffff;
    border-radius: 12rpx;
    padding: 0 24rpx;
    min-height: 88rpx;
    font-size: 30rpx;
    color: #333;
    .form-input {
      flex: 1;
      background: transparent;
      border: none;
      outline: none;
      font-size: 30rpx;
      color: #333;
      padding: 24rpx 0;
      &::placeholder {
        color: #bbb;
      }
    }
    .input-pl {
      color: #bbb;
      font-size: 30rpx;
    }
    .ibonjinru {
      color: $main-color;
      font-size: 32rpx;
      margin-left: 16rpx;
    }
  }
}

.dianPuLeiXing {
  display: flex;
  gap: 40rpx;
  label {
    display: flex;
    align-items: center;
    font-size: 30rpx;
    color: #333;
    .radio_active {
      color: $main-color;
    }
    radio {
      margin-right: 12rpx;
      transform: scale(0.8);
      accent-color: $main-color;
    }
    &.radio_active text {
      color: $main-color;
    }
  }
}

.sel-label,
.sel-name {
  color: #333;
  font-size: 30rpx;
}
.input-pl {
  color: #bbb;
  font-size: 30rpx;
}

.TimeBorder {
  min-width: 120rpx;
  padding: 12rpx 24rpx;
  border: 1rpx solid $main-color;
  border-radius: 8rpx;
  color: $main-color;
  font-size: 30rpx;
  background: $bg-color;
  text-align: center;
}

.line {
  width: 32rpx;
  text-align: center;
  color: #bbb;
  font-size: 32rpx;
  margin: 0 8rpx;
}

.form-up {
  background: $bg-color;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(251, 89, 4, 0.04);
  padding: 0 24rpx 32rpx 24rpx;
  .form-label {
    color: #333;
    font-size: 30rpx;
    font-weight: 500;
    margin-bottom: 12rpx;
    .icon-requird {
      color: $main-color;
      margin-left: 8rpx;
      font-size: 24rpx;
    }
  }
  .form-value {
    display: flex;
    align-items: center;
    gap: 16rpx;
  }
}

.upload-view {
  width: 144rpx;
  height: 144rpx;
  background: #f8f8f8;
  border: 2rpx dashed $main-color;
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  color: $main-color;
  font-size: 60rpx;
  .ibonxinzeng {
    font-size: 60rpx;
  }
}

.cata-img {
  width: 144rpx;
  height: 144rpx;
  border-radius: 16rpx;
  margin-right: 16rpx;
  object-fit: cover;
  border: 2rpx solid $main-color;
}

.fixed-bottom {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background: $bg-color;
  box-shadow: 0 -2rpx 16rpx rgba(0, 0, 0, 0.04);
  padding: 24rpx 32rpx;
  z-index: 10;
  .sub-btn {
    width: 100%;
    background: $main-color;
    color: $bg-color;
    font-size: 34rpx;
    border-radius: 12rpx;
    text-align: center;
    padding: 24rpx 0;
    font-weight: 600;
    letter-spacing: 2rpx;
    box-shadow: 0 4rpx 16rpx rgba(251, 89, 4, 0.08);
    transition: background 0.2s;
    &:active {
      background: darken($main-color, 8%);
    }
  }
}

.clearfix::after {
  content: "";
  display: block;
  clear: both;
}

.float_left {
  float: left;
}
::v-deep .u-form-item--left {
  padding-left: 24rpx;
}
</style>
